The boolean expression is true
34 > 2 || 5 == 7 ------ ----- true false -------------- true
because all OR needs is one true.
The above expression evaluates to true because at least one operand was true. In fact, as soon as the first true is detected, you know that the entire expression must be true, because true OR anything is true.
34 > 2 || 5 == 7 ------ ----- true does not matter -------------- true
As an optimization, Java evaluates an expression only as
far as needed to determine its value.
When program runs, as soon as 34 > 2
is
found to be true, the entire expression is known
to be true, and evaluation goes no further.
This type of optimization is called short-circuit evaluation.
(Just as it is with AND.)
Here is a full Java program that implements the car purchase decision.
// Sports Car Purchase // // You need $25000 in cash or credit // import java.util.Scanner; class HotWheels { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int cash, credit ; // get the cash System.out.print("How much cash? "); cash = scan.nextInt() ; // get the credit line System.out.print("How much credit? "); credit = scan.nextInt() ; // check that at least one qualification is met if ( cash >= 25000 || credit >= 25000 ) System.out.println("Enough to buy this car!" ); else System.out.println("What about a Yugo?" ); } }
Compile and run the program with various values of cash and credit to check that you understand how OR works.
What does the program do if the user enters negative numbers?